from mqtt import MQTTClient
import time
import json

# mqtt服务器地址
mqtt_server = "nps.kelebb.com"
CLIENT_ID = "ESP8266_" + str(time.time())
TOPIC = "esp8266"
mqtt_username = 'nodemcu1'
mqtt_password = 'nodemcu1'
mqttClient = ''


def link_mqtt():
    global mqttClient
    mqttClient = MQTTClient(CLIENT_ID, mqtt_server, 21883, mqtt_username, mqtt_password)
    mqttClient.set_callback(sub_cb)
    mqttClient.connect()
    mqttClient.subscribe(TOPIC)
    print("Connected to %s, subscribed to %s topic" % (mqtt_server, TOPIC))
    # try:
    #     while 1:
    #         # micropython.mem_info()
    #         # publish_msg()
    #         # mqttClient.wait_msg()
    #         # time.sleep(3)
    # finally:
    #     mqttClient.disconnect()


def publish_msg(d):
    if mqttClient == '':
        link_mqtt()
    json_str = json.dumps(d)
    print("开始推送消息：", json_str)
    mqttClient.publish("esp8266_notify", json_str)


def sub_cb(topic, msg):
    print((topic, msg))
    # turn_angle(msg)
    # if msg == b"on":
    #         led.value(0)
    #         state = 1
    #         print("1")
    # elif msg == b"off":
    #         led.value(1)
    #         state = 0
    #         print("0")
    # elif msg == b"toggle":
    #         # LED is inversed, so setting it to current state
    #         # value will make it toggle
    #         led.value(state)
    #         state = 1 - state
